var $ = jQuery = layui.jquery;

$(function () {
  //清空表单数据
  $("#suk").val("");
  //初始化
  cout()
  cout2()


  $(document).on('click', ".close.pull-right", function () {
    $(this).parents('.popover ').hide();
  });
  //添加规格
  $("#suk_addsuk").click(function () {
    $.ajax({
      url: "/assets/js/data/tags.json",
      data: {
        type: 1,
        pid: 0,
        model_id: "4"
      },
      success: function (res) {

        var size = $(".suk_body>section").size() + 1;
        //第一个规格添加图片
        var ispic = "";
        var ispicwrap = '';


        var suk_select = ""
        suk_select += '<section class="panel panel-default m-b-none" data-id="select-' + size + '">' +
          '<header class="panel-heading bg-light no-border">' +
          '<div class="clearfix">' +
          '<select style="width:260px" class="chosen-select" data-placeholder="请选择规格">' +
          '<option value=""></option>';
        $.each(res, function (index, item) {
          suk_select += '<option value="' + item.id + '">' + item.name + '</option>'
        })

        suk_select += '</select> <a class="hide btn btn-sm btn-default popover-hide" title=""  data-html="true" data-toggle="popover" data-placement="bottom" data-original-title=\'<button type="button" class="close pull-right" data-dismiss="popover">&times;</button>添加规格\'' +
          'data-content="<div class=\'form-inline\'><div class=\'form-group \'><input type=\'text\' placeholder=\'请输入规格\' class=\'form-control input-sm m-l js-tas-input\'></div><a class=\'btn btn-success btn-sm js-tags \' href=\'javascript:;\'>保存</a></div>">添加规格</a>' +
          ispic +
          '<a class="close suk_close" id="select-' + size + '" >×</a>' +
          '</div>' +
          '</header>' +
          '<div class="list-group no-radius alt">' +
          '<div href="#" class="list-group-item">' +
          '<input type="text" class="tags" value="" />' +
          '</div>' +
          '</div>' +
          ispicwrap +
          '</section>';


        $('.suk_body').append(suk_select);


        if ($(".chosen-select").length) {
          $('.chosen-select').chosen({
            placeholder_text: "选择规则"
          });

          $('.tags').tagsInput({
            width: 'auto',
            height: '43px',
            defaultText: '输入规格值并回车确认',
            onChange: function (elem, elem_tags) {
              //console.log(JSON.stringify(elem));
              //console.log(elem_tags);
              drawThead() //绘制表头
              drawTbody() //绘制表格
              //当有规格添加时锁定价格和库存
              $("#present_price").attr("disabled", true);
              $("input[name='weight']").attr("disabled", true);

            }
          });
        }
        cout();

        $("[data-toggle=popover]").popover();


      }
    })
  })


  //批量设置价格
  $(document).on('click', "#js-batch-price", function () {
    var price = $("#price-batch-txt").val();
    $(".sku_price").val(price);
    chandate();
    $('.popover-hide').popover('hide');
  });
  $(document).on('click', "#js-batch-stock", function () {
    var stock = $("#stock-batch-txt").val();
    $(".sku_stock").val(stock);
    chandate();
    $('.popover-hide').popover('hide');
  });
  $(document).on('click', "#js-batch-weight", function () {
    var weight = $("#weight-batch-txt").val();
    $(".sku_weight").val(weight);
    chandate();
    $('.popover-hide').popover('hide');
  });

  //记录添加规格的个数
  function cout() {
    var size = $(".suk_body>section").size();
    if (size != 0) {
      $(".suk_heading").removeClass("hide");
      $(".suk_body, .suk_body_box").removeClass("hide");
      $(".suk_table").removeClass("hide");
    } else {
      $(".suk_heading").addClass("hide");
      $(".suk_body, .suk_body_box").addClass("hide");
      $(".suk_table").addClass("hide");
      $("#present_price").attr("disabled", false);
      $("input[name='weight']").attr("disabled", false);
    }
    if (size > 2) {
      $("#suk_addsuk").addClass("hide");
    } else {
      $("#suk_addsuk").removeClass("hide");
    }
  }

  //记录添加规格的个数
  function cout2() {

    var size = tagIns1.names.length;
    if (size > 0) {
      $(".guige_list").show();
      $(".suk_table").show();
    } else {
      $(".guige_list").hide();
      $(".suk_table").hide();
    }
    if (size > 2) {
      $("#suk_addsuk").addClass("hide");
    } else {
      $("#suk_addsuk").removeClass("hide");
    }
  }
  window.cout2 = cout2;

  //添加一级规格

  $(document).on('change', '.chosen-select', function () {
    var val = $('.chosen-select').val(); //获取选中的值
    var tex = $('.chosen-select option:selected').text(); //选择选择的文字
    drawThead() //绘制表头
    //console.log(val);
    //console.log(tex);
  })

//绘制表格
  function zp_drawTbody(arr) {
    $(".suk_table").removeClass("hide");
    var type = gettype2();
    var narr = getstru2();

    var narr2 = arr;
    var i = 0;
    var tbHtml = "";
    var tbHtml1 = "";
    var tbHtml2 = "";
    var v_sku_price = "";
    var v_sku_stock = "";
    var v_sku_weight = "";
    var v_sku_code = "";
    //获取上次chucun的数据；
    var predatas = $("#suk").val();
     console.log(type);
     console.log(narr);

    if (predatas) {
      var predata = $.parseJSON(predatas).data;
    }
    //console.log(predata);

    $.each(narr, function (k, v) {
      if (v.ch) {
        $.each(v.ch, function (_k, _v) {
          if (_v.ch) {

            $.each(_v.ch, function (__k, __v) {

              //输出三级表格
              //  var v_sku_price,v_sku_stock,v_sku_code;
              // if(predata){
              //     if(predata[k]['ch']){
              //     if(predata[k]['ch'][_k]['ch']){
              //         console.log(predata[k]['ch'][_k]["ch"][__k])
              //         var d_=predata[k]['ch'][_k]["ch"][__k];
              //     if(d_){
              //     v_sku_price= d_['sku_price'];
              //     v_sku_stock= d_['sku_stock'];
              //     v_sku_code= d_['sku_code'];
              //     }
              //     }
              //     }
              // }
              try {
                // 可能会导致错误的代码
                var v_sku_price = "";
                var v_sku_stock = "";
                var v_sku_code = "";
                var d_ = predata[k]['ch'][_k]["ch"][__k];
                v_sku_price = d_['sku_price'] ? d_['sku_price'] : "";
                v_sku_stock = d_['sku_stock'] ? d_['sku_stock'] : "";
                v_sku_code = d_['sku_code'] ? d_['sku_code'] : "";
                v_sku_weight = d_['sku_weight'] ? d_['sku_weight'] : "";
              } catch (error) {
                // 在错误发生时怎么处理
              }
              var g = v.ch.length * _v.ch.length;
              tbHtml += "<tr>";
              if (i % g == 0) {
                tbHtml += "<td rowspan=" + v.ch.length * _v.ch.length + ">" + v.name + "</td>";
              }
              if (__k % _v.ch.length == 0) {
                tbHtml += "<td rowspan=" + _v.ch.length + ">" + _v.name + "</td>";
              }
              tbHtml += "<td rowspan='1'>" + __v.name + "</td>";
              tbHtml += '<td><input type="text" placeholder="价格" value="' + v_sku_price + '" class="tdinput sku_price"  id="sku_price_' + i + '"></td>\
<td><input type="text" placeholder="库存" value="' + v_sku_stock + '" class="tdinput sku_stock" id="sku_stock_' + i + '"></td>\
<td><input type="text" placeholder="编码" value="' + v_sku_code + '" class="tdinput" id="sku_code_' + i + '"></td>';
              tbHtml += "</tr>";
              var sku_price = "#sku_price_" + i;
              var sku_stock = "#sku_stock_" + i;
              var sku_code = "#sku_code_" + i;
              var sku_weight = "#sku_weight_" + i;
              __v.sku_weight = $(sku_weight).val();
              __v.sku_price = $(sku_price).val();
              __v.sku_stock = $(sku_stock).val();
              __v.sku_code = $(sku_code).val();
              i = i + 1;
            })
          } else {
            //输出二级表格
            // var v_sku_price,v_sku_stock,v_sku_code;

            // if(predata){
            //     if(predata[k]['ch']){
            //         console.log(predata[k]["ch"][_k])
            //         var d_=predata[k]["ch"][_k];
            //     if(d_){
            //     v_sku_price= d_['sku_price'];
            //     v_sku_stock= d_['sku_stock'];
            //     v_sku_code= d_['sku_code'];
            //     }
            //     }
            // }
            try {
              // 可能会导致错误的代码
              var d_ = predata[k]["ch"][_k];
              v_sku_price = d_['sku_price'] ? d_['sku_price'] : "";
              v_sku_stock = d_['sku_stock'] ? d_['sku_stock'] : "";
              v_sku_weight = d_['sku_weight'] ? d_['sku_weight'] : "";
              v_sku_code = d_['sku_code'] ? d_['sku_code'] : "";
            } catch (error) {
              // 在错误发生时怎么处理
            }
            tbHtml += "<tr>";
            if (_k % v.ch.length == 0) {
              tbHtml += "<td rowspan=" + v.ch.length + ">" + v.name + "</td>";
            }
            tbHtml += "<td rowspan='1'>" + _v.name + "</td>";
            tbHtml += '<td><input type="text" placeholder="价格" value="' + v_sku_price + '" class="tdinput sku_price"  id="sku_price_' + i + '"></td>\
<td><input type="text" placeholder="库存" value="' + v_sku_stock + '" class="tdinput sku_stock" id="sku_stock_' + i + '"></td>\
<td><input type="text" placeholder="编码" value="' + v_sku_code + '" class="tdinput" id="sku_code_' + i + '"></td>';
            tbHtml += "</tr>";
            var sku_price = "#sku_price_" + i;
            var sku_stock = "#sku_stock_" + i;
            var sku_weight = "#sku_weight_" + i;
            var sku_code = "#sku_code_" + i;
            _v.sku_price = $(sku_price).val();
            _v.sku_stock = $(sku_stock).val();
            _v.sku_weight = $(sku_weight).val();
            _v.sku_code = $(sku_code).val();
            i = i + 1;
          }
        })
      } else {
        //输出一级表格

        if (predata) {
          if (predata[k]) {
            //console.log(predata[k]['sku_price'] != null)
            v_sku_price = predata[k]['sku_price'] ? predata[k]['sku_price'] : "";
            v_sku_stock = predata[k]['sku_stock'] ? predata[k]['sku_stock'] : "";
            v_sku_weight = predata[k]['sku_weight'] ? predata[k]['sku_weight'] : "";
            v_sku_code = predata[k]['sku_code'] ? predata[k]['sku_code'] : "";
          }
        }
        tbHtml += "<tr>";
        tbHtml += "<td rowspan='1'>" + v.name + "</td>";
        tbHtml += '<td><input type="text" placeholder="价格" value="' + v_sku_price + '" class="tdinput sku_price"  id="sku_price_' + i + '"></td>' +
          '<td><input type="text" placeholder="库存" value="' + v_sku_stock + '" class="tdinput sku_stock" id="sku_stock_' + i + '"></td>' +
          '<td><input type="text" placeholder="编码" value="' + v_sku_code + '" class="tdinput" id="sku_code_' + i + '"></td>';
        tbHtml += "</tr>";
        var sku_price = "#sku_price_" + i;
        var sku_stock = "#sku_stock_" + i;
        var sku_weight = "#sku_weight_" + i;
        var sku_code = "#sku_code_" + i;

        v.sku_price = $(sku_price).val();
        v.sku_stock = $(sku_stock).val();
        v.sku_weight = $(sku_weight).val();
        v.sku_code = $(sku_code).val();
        i = i + 1;
      }
    })
    //console.log(tbHtml1);

    $(".suk_table table tbody").html(tbHtml);
    //拼装储存数据
    var suk_info = {
      "type": type,
      "data": narr,
      "is_pic": $("#js-addImg-function:checked").val() ? $("#js-addImg-function:checked").val() : 0
    }
    if (type.length > 0) {
      $("#suk").val(JSON.stringify(suk_info));
    } else {
      $("#suk").val("");
    }

  }

  //绘制表头
  function zp_rawThead(arr) {

    var narr = arr;

    var thHtml = "";
    thHtml += "";
    thHtml += "<tr>";
    for (cSort = 0; cSort <= narr.length - 1; cSort++) {
      thHtml += '<th class="active">' + narr[cSort] + "</th>";
    }
    thHtml += '<th class="active">价格(元)</th><th class="active">库存</th><th class="active">单品编码</th>';
    thHtml += "</tr>";
    thHtml += "";
    $(".suk_table").removeClass("hide");
    $(".suk_table table thead").html(thHtml);
  }

  //点击绘制表头测试
  $('body').on('click', '.js_drawHead', function () {
    var arr = ["尺寸", "尺码"];
    zp_rawThead(arr)
  });

  window.zp_rawThead = zp_rawThead;
  window.zp_drawTbody = zp_drawTbody;



  //点击绘制表格测试
  $('body').on('click', '.js_drawBody', function () {
    var arr = [
      {
        name: "xl",
        type: "尺寸",
        pic: undefined,
        ch: [
          {name: "kg", type: "克重",sku_code: undefined,  sku_price: undefined, sku_stock: undefined, sku_weight: undefined},
          {name: "g", type: "克重", sku_code: undefined, sku_price: undefined, sku_stock: undefined, sku_weight: undefined}
        ]
      },
      {
        name: "l",
        type: "尺寸",
        pic: undefined,
        ch: [
          {name: "kg", type: "克重", sku_code: undefined, sku_price: undefined, sku_stock: undefined, sku_weight: undefined},
          {name: "g", type: "克重", sku_code:  undefined, sku_price: undefined, sku_stock: undefined, sku_weight: undefined}
        ]
      }
    ]
    zp_drawTbody(arr)
  });


  //绘制表头
  function drawThead() {
    var arr = $('.chosen-select');
    var narr = [];
    $.each(arr, function (k, v) {
      if ($(v).find("option:selected").text().length > 0)
        narr.push($(v).find("option:selected").text());
    })
    // console.log(narr);
    var thHtml = "";
    thHtml += "";
    thHtml += "<tr>";
    for (cSort = 0; cSort <= narr.length - 1; cSort++) {
      thHtml += '<th class="active">' + narr[cSort] + "</th>";
    }
    thHtml += '<th class="active">价格(元)</th><th class="active">库存</th><th class="active">单品编码</th>';
    thHtml += "</tr>";
    thHtml += "";
    $(".suk_table").removeClass("hide");
    $(".suk_table table thead").html(thHtml);
  }


  //绘制表格
  function drawTbody() {
    $(".suk_table").removeClass("hide");
    var type = gettype();
    var narr = getstru();
    var i = 0;
    var tbHtml = "";
    var tbHtml1 = "";
    var tbHtml2 = "";
    var v_sku_price = "";
    var v_sku_stock = "";
    var v_sku_weight = "";
    var v_sku_code = "";
    //获取上次chucun的数据；
    var predatas = $("#suk").val();


    if (predatas) {
      var predata = $.parseJSON(predatas).data;
    }
    //console.log(predata);

    // console.log(narr);

    $.each(narr, function (k, v) {
      if (v.ch) {
        $.each(v.ch, function (_k, _v) {
          if (_v.ch) {

            $.each(_v.ch, function (__k, __v) {

              //输出三级表格
              //  var v_sku_price,v_sku_stock,v_sku_code;
              // if(predata){
              //     if(predata[k]['ch']){
              //     if(predata[k]['ch'][_k]['ch']){
              //         console.log(predata[k]['ch'][_k]["ch"][__k])
              //         var d_=predata[k]['ch'][_k]["ch"][__k];
              //     if(d_){
              //     v_sku_price= d_['sku_price'];
              //     v_sku_stock= d_['sku_stock'];
              //     v_sku_code= d_['sku_code'];
              //     }
              //     }
              //     }
              // }
              try {
                // 可能会导致错误的代码
                var v_sku_price = "";
                var v_sku_stock = "";
                var v_sku_code = "";
                var d_ = predata[k]['ch'][_k]["ch"][__k];
                v_sku_price = d_['sku_price'] ? d_['sku_price'] : "";
                v_sku_stock = d_['sku_stock'] ? d_['sku_stock'] : "";
                v_sku_code = d_['sku_code'] ? d_['sku_code'] : "";
                v_sku_weight = d_['sku_weight'] ? d_['sku_weight'] : "";
              } catch (error) {
                // 在错误发生时怎么处理
              }
              var g = v.ch.length * _v.ch.length;
              tbHtml += "<tr>";
              if (i % g == 0) {
                tbHtml += "<td rowspan=" + v.ch.length * _v.ch.length + ">" + v.name + "</td>";
              }
              if (__k % _v.ch.length == 0) {
                tbHtml += "<td rowspan=" + _v.ch.length + ">" + _v.name + "</td>";
              }
              tbHtml += "<td rowspan='1'>" + __v.name + "</td>";
              tbHtml += '<td><input type="text" placeholder="价格" value="' + v_sku_price + '" class="tdinput sku_price"  id="sku_price_' + i + '"></td>\
<td><input type="text" placeholder="库存" value="' + v_sku_stock + '" class="tdinput sku_stock" id="sku_stock_' + i + '"></td>\
<td><input type="text" placeholder="编码" value="' + v_sku_code + '" class="tdinput" id="sku_code_' + i + '"></td>';
              tbHtml += "</tr>";
              var sku_price = "#sku_price_" + i;
              var sku_stock = "#sku_stock_" + i;
              var sku_code = "#sku_code_" + i;
              var sku_weight = "#sku_weight_" + i;
              __v.sku_weight = $(sku_weight).val();
              __v.sku_price = $(sku_price).val();
              __v.sku_stock = $(sku_stock).val();
              __v.sku_code = $(sku_code).val();
              i = i + 1;
            })
          } else {
            //输出二级表格
            // var v_sku_price,v_sku_stock,v_sku_code;

            // if(predata){
            //     if(predata[k]['ch']){
            //         console.log(predata[k]["ch"][_k])
            //         var d_=predata[k]["ch"][_k];
            //     if(d_){
            //     v_sku_price= d_['sku_price'];
            //     v_sku_stock= d_['sku_stock'];
            //     v_sku_code= d_['sku_code'];
            //     }
            //     }
            // }
            try {
              // 可能会导致错误的代码
              var d_ = predata[k]["ch"][_k];
              v_sku_price = d_['sku_price'] ? d_['sku_price'] : "";
              v_sku_stock = d_['sku_stock'] ? d_['sku_stock'] : "";
              v_sku_weight = d_['sku_weight'] ? d_['sku_weight'] : "";
              v_sku_code = d_['sku_code'] ? d_['sku_code'] : "";
            } catch (error) {
              // 在错误发生时怎么处理
            }
            tbHtml += "<tr>";
            if (_k % v.ch.length == 0) {
              tbHtml += "<td rowspan=" + v.ch.length + ">" + v.name + "</td>";
            }
            tbHtml += "<td rowspan='1'>" + _v.name + "</td>";
            tbHtml += '<td><input type="text" placeholder="价格" value="' + v_sku_price + '" class="tdinput sku_price"  id="sku_price_' + i + '"></td>\
<td><input type="text" placeholder="库存" value="' + v_sku_stock + '" class="tdinput sku_stock" id="sku_stock_' + i + '"></td>\
<td><input type="text" placeholder="编码" value="' + v_sku_code + '" class="tdinput" id="sku_code_' + i + '"></td>';
            tbHtml += "</tr>";
            var sku_price = "#sku_price_" + i;
            var sku_stock = "#sku_stock_" + i;
            var sku_weight = "#sku_weight_" + i;
            var sku_code = "#sku_code_" + i;
            _v.sku_price = $(sku_price).val();
            _v.sku_stock = $(sku_stock).val();
            _v.sku_weight = $(sku_weight).val();
            _v.sku_code = $(sku_code).val();
            i = i + 1;
          }
        })
      } else {
        //输出一级表格

        if (predata) {
          if (predata[k]) {
            //console.log(predata[k]['sku_price'] != null)
            v_sku_price = predata[k]['sku_price'] ? predata[k]['sku_price'] : "";
            v_sku_stock = predata[k]['sku_stock'] ? predata[k]['sku_stock'] : "";
            v_sku_weight = predata[k]['sku_weight'] ? predata[k]['sku_weight'] : "";
            v_sku_code = predata[k]['sku_code'] ? predata[k]['sku_code'] : "";
          }
        }
        tbHtml += "<tr>";
        tbHtml += "<td rowspan='1'>" + v.name + "</td>";
        tbHtml += '<td><input type="text" placeholder="价格" value="' + v_sku_price + '" class="tdinput sku_price"  id="sku_price_' + i + '"></td>' +
          '<td><input type="text" placeholder="库存" value="' + v_sku_stock + '" class="tdinput sku_stock" id="sku_stock_' + i + '"></td>' +
          '<td><input type="text" placeholder="编码" value="' + v_sku_code + '" class="tdinput" id="sku_code_' + i + '"></td>';
        tbHtml += "</tr>";
        var sku_price = "#sku_price_" + i;
        var sku_stock = "#sku_stock_" + i;
        var sku_weight = "#sku_weight_" + i;
        var sku_code = "#sku_code_" + i;

        v.sku_price = $(sku_price).val();
        v.sku_stock = $(sku_stock).val();
        v.sku_weight = $(sku_weight).val();
        v.sku_code = $(sku_code).val();
        i = i + 1;
      }
    })
    //console.log(tbHtml1);

    $(".suk_table table tbody").html(tbHtml);
    //拼装储存数据
    var suk_info = {
      "type": type,
      "data": narr,
      "is_pic": $("#js-addImg-function:checked").val() ? $("#js-addImg-function:checked").val() : 0
    }
    if (type.length > 0) {
      $("#suk").val(JSON.stringify(suk_info));
    } else {
      $("#suk").val("");
    }

  }


  // 储存数据
  $(document).on('change', '.sku_price,.sku_stock,.sku_code,.sku_weight', function () {
    chandate();
  })

  function chandate() {
    var type = gettype();
    var narr = getstru();
    localStorage.setItem('$narr', JSON.stringify(narr));

    var ntr = $(".suk_table").find("tbody>tr");
    var bianli_arr = [];
    $.each(ntr, function (k, v) {
      var _obj = {};
      _obj.sku_price = $("#sku_price_" + k).val();
      _obj.sku_stock = $("#sku_stock_" + k).val();
      _obj.sku_weight = $("#sku_weight_" + k).val();
      _obj.sku_code = $("#sku_code_" + k).val();
      bianli_arr.push(_obj);
    });

    //console.log(JSON.stringify(bianli_arr));

    function bianli(arr) {
      for (var i = 0; i < arr.length; i++) {
        try {
          if (arr[i].ch) {
            bianli(arr[i].ch);
          } else {
            var sh = bianli_arr.shift();
            //console.log(sh);
            //console.log(arr[i]);
            for (var k in sh) {
              arr[i][k] = sh[k];
            }
          }
        } catch (e) {
        }
      }
      return arr;
    }

    //console.log(JSON.stringify(narr));
    var result = bianli(JSON.parse(localStorage.getItem("$narr")));
    // console.log(JSON.stringify(result));

    //拼装储存数据
    var suk_info = {
      "type": type,
      "data": result,
      "is_pic": $("#js-addImg-function:checked").val() ? $("#js-addImg-function:checked").val() : 0
    }

    if (type.length > 0) {
      $("#suk").val(JSON.stringify(suk_info));
    } else {
      $("#suk").val("");
    }
    //关联价格
    var pricearr = [];
    $.each($(".sku_price"), function () {
      pricearr.push($(this).val());
    })
    pricearr.sort(function (a, b) {
      return a - b;
    });
    var discount_price = $("#discount_price").val();
    if (discount_price == "") {
      discount_price = 0;
    }
    if (pricearr[pricearr.length - 1] == pricearr[0]) {
      $("#present_price").val(pricearr[0]);
      var p = '{"present_price":"' + pricearr[0] + '","discount_price":"' + discount_price + '"}'
      $("#price").val(p);
    } else {
      $("#present_price").val(pricearr[0] + "-" + pricearr[pricearr.length - 1]);
      var p = '{"present_price":"' + pricearr[0] + '-' + pricearr[pricearr.length - 1] + '","discount_price":"' + discount_price + '"}'
      $("#price").val(p);
    }
    //关联库存
    var total_stockarr = 0;
    $.each($(".sku_stock"), function () {
      total_stockarr = Number($(this).val()) + total_stockarr;
    })
    $("input[name='total_stock']").val(total_stockarr);
  }


  //获取类型
  function gettype2() {
    var type = tagIns1.names;
    return type;
  }

  //获取类型
  function gettype() {
    var arr = $('.chosen-select');
    var type = [];
    $.each(arr, function (k, v) {
      if ($(v).find("option:selected").text().length > 0)
        type.push($(v).find("option:selected").text());
    })
    return type;
  }

  //数据机构
  function getstru() {
    var narr = [];

    $.each($(".tags"), function (k, v) {
      var type = gettype();
      console.log(type);
      //narr.push($(v).val());
      item = $(v).val().split(",");
      //获取类型

      if (item[0].length != 0) {
        if (k == 0) {
          $.each(item, function (n, m) {
            var obj = {};
            obj.name = m;
            obj.type = type[k]
            // console.log(obj);
            obj.pic = $("#cover_id_" + n).val();
            narr.push(obj);
          })

        }
        if (k == 1) {
          var ch_arr = [];
          $.each(item, function (nn, mm) {
            //console.log(mm)
            var _obj = {};
            _obj.name = mm;
            _obj.type = type[k]
            ch_arr.push(_obj);
          });
          for (var i = 0; i < narr.length; i++) {
            narr[i].ch = ch_arr;
          }
        }
        if (k == 2) {
          var ch_arr = [];
          $.each(item, function (nn, mm) {
            //console.log(mm)
            var _obj = {};
            _obj.name = mm;
            _obj.type = type[k]
            ch_arr.push(_obj);
          });
          for (var i = 0; i < narr.length; i++) {
            for (var j = 0; j < narr[i].ch.length; j++) {
              var tmp = narr[i].ch;
              tmp[j].ch = ch_arr;
            }
          }
        }

      }

    })

    console.log(narr)
    return narr;
  }

  //数据机构
  function getstru2() {
    var narr = [];

    $.each($(document).find(".tags_input"), function (k, v) {
      var type = gettype2();
      item = $(v).val().split(",");
      //获取类型


      if (item[0].length != 0) {
        if (k == 0) {
          $.each(item, function (n, m) {
            var obj = {};
            obj.name = m;
            obj.type = type[k]
            // console.log(obj);
            obj.pic = $("#cover_id_" + n).val();
            narr.push(obj);
          })

        }
        if (k == 1) {
          var ch_arr = [];
          $.each(item, function (nn, mm) {
            //console.log(mm)
            var _obj = {};
            _obj.name = mm;
            _obj.type = type[k]
            ch_arr.push(_obj);
          });
          for (var i = 0; i < narr.length; i++) {
            narr[i].ch = ch_arr;
          }
        }
        if (k == 2) {
          var ch_arr = [];
          $.each(item, function (nn, mm) {
            //console.log(mm)
            var _obj = {};
            _obj.name = mm;
            _obj.type = type[k]
            ch_arr.push(_obj);
          });
          for (var i = 0; i < narr.length; i++) {
            for (var j = 0; j < narr[i].ch.length; j++) {
              var tmp = narr[i].ch;
              tmp[j].ch = ch_arr;
            }
          }
        }

      }

    })
    // console.log(narr);
    return narr;
  }


  //删除规格
  $(document).on('click', ".suk_close", function () {
    var select = $(this).attr("id");

    $('[data-id="' + select + '"]').remove();
    $.each($("section.suk_body>section"), function (i, v) {
      i = i + 1;

      $(v).attr("data-id", "select-" + i);
      $(v).find(".suk_close").attr("id", "select-" + i);
    })
    drawThead() //绘制表头
    drawTbody() //绘制表格
    cout();
  })
  $(document).on('click', '.js-tags', function () {
    var section = $(this).parents('section').attr('data-id');
    section = '[data-id=' + section + ']';
    var input = $(section).find("input.js-tas-input").val();
    if (input.length == 0) {
      toastr.error("请填写规格！");
      return false;
    }
    $.ajax({
      type: "POST",
      url: "/admin/tags/ajaxaddtags",
      data: {
        name: input,
        type: 1,
        model_id: "4"
      },
      success: function (res) {
        if (res.errno == 0) {
          $(section).find("select.chosen-select").append("<option value=" + res.id + " selected>" + res.name + "</option>");
          $('.chosen-select').trigger("liszt:updated");
          $('.popover-hide').popover('hide');
          toastr.success("添加规格成功！");
        } else {
          toastr.error(res.errmsg);
        }
      }

    })
  })

  //关联价格
  $(document).on('change', '#present_price,#discount_price', function () {
    var discount_price;
    if ($("#discount_price").val()) {
      discount_price = $("#discount_price").val()
    } else {
      discount_price = 0
    }
    $("#price").val('{"present_price":"' + $("#present_price").val() + '","discount_price":"' + discount_price + '"}')
  })
})

